# 系统通知管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from myadmin.models import SystemNotice

# 系统通知管理
def index(request, pIndex=1):
    """系统通知列表页"""
    nlist = SystemNotice.objects.all()
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            nlist = nlist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理
    kw = request.GET.get("keyword", None)
    if kw:
        nlist = nlist.filter(
            Q(title__contains=kw) | 
            Q(content__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 类型筛选
    notice_type = request.GET.get('notice_type', '')
    if notice_type:
        nlist = nlist.filter(notice_type=notice_type)
        mywhere.append(f'notice_type={notice_type}')
    
    # 状态筛选
    is_active = request.GET.get('is_active', '')
    if is_active in ['0', '1']:
        nlist = nlist.filter(is_active=is_active)
        mywhere.append(f'is_active={is_active}')
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(nlist, 10)  # 每页10条
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    context = {
        "noticelist": list2,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_type': notice_type,
        'selected_active': is_active
    }
    return render(request, "myadmin/systemnotice/index.html", context)

def add(request):
    """加载系统通知添加表单"""
    # 获取通知类型选项用于表单下拉框
    notice_types = SystemNotice.NOTICE_TYPE_CHOICES
    context = {'notice_types': notice_types}
    return render(request, "myadmin/systemnotice/add.html", context)

def insert(request):
    """执行系统通知添加"""
    try:
        ob = SystemNotice()
        ob.title = request.POST.get('title').strip()
        ob.content = request.POST.get('content').strip()
        ob.notice_type = request.POST.get('notice_type')
        ob.is_important = request.POST.get('is_important') == 'on'
        ob.is_active = request.POST.get('is_active') == 'on'
        
        # 处理过期时间
        expire_time_str = request.POST.get('expire_time', '')
        if expire_time_str:
            ob.expire_time = datetime.strptime(expire_time_str, '%Y-%m-%d %H:%M:%S')
        
        ob.save()
        context = {'info': "发布成功！"}
    except Exception as err:
        print(err)
        context = {'info': "发布失败！"}
    return render(request, "myadmin/info.html", context)

def edit(request, nid=0):
    """加载系统通知编辑表单"""
    try:
        ob = SystemNotice.objects.get(notice_id=nid)
        notice_types = SystemNotice.NOTICE_TYPE_CHOICES
        context = {
            'notice': ob, 
            'notice_types': notice_types
        }
        return render(request, "myadmin/systemnotice/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': "没有找到要修改的通知！"}
    return render(request, "myadmin/info.html", context)

def update(request, nid):
    """执行系统通知编辑"""
    try:
        # 获取通知对象
        ob = SystemNotice.objects.get(notice_id=nid)
        
        # 验证必填字段
        if not request.POST.get('title').strip():
            raise ValueError('通知标题为必填项！')
        if not request.POST.get('content').strip():
            raise ValueError('通知内容为必填项！')
        
        # 更新字段
        ob.title = request.POST.get('title').strip()
        ob.content = request.POST.get('content').strip()
        ob.notice_type = request.POST.get('notice_type')
        ob.is_important = request.POST.get('is_important') == 'on'
        ob.is_active = request.POST.get('is_active') == 'on'
        
        # 处理过期时间
        expire_time_str = request.POST.get('expire_time', '')
        if expire_time_str:
            expire_time_str = expire_time_str.replace('T', ' ')
            ob.expire_time = datetime.strptime(expire_time_str, '%Y-%m-%d %H:%M:%S')
        else:
            ob.expire_time = None
        
        ob.save()
        context = {'info': "修改成功！"}
    
    except SystemNotice.DoesNotExist:
        context = {'info': "修改失败：通知不存在！"}
    except ValueError as e:
        context = {'info': f"修改失败：{str(e)}"}
    except Exception as e:
        print(f"修改错误详情：{str(e)}")
        context = {'info': f"修改失败：{str(e)}"}
    
    return render(request, "myadmin/info.html", context)

def delete(request, nid=0):
    """执行系统通知删除"""
    try:
        ob = SystemNotice.objects.get(notice_id=nid)
        ob.delete()
        context = {'info': "删除成功！"}
    except SystemNotice.DoesNotExist:
        context = {'info': "删除失败：通知不存在！"}
    except Exception as err:
        print(f"删除通知时出错: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)